package com.sgb.kjwl.view.ui.fragment.self;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragApprovalManageBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.self.ApplyTypeData;
import com.sgb.kjwl.model.entity.self.ApprovalListEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.adapter.self.ApproveManageAdapter;
import com.sgb.kjwl.viewmodel.self.ApprovalModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * @author: 王彬臣
 * @date: 2021/2/20
 * @Description: 审批列表
 */
public class ApprovalManagerFragment extends AppLazyFragment {
    private FragApprovalManageBinding binding;
    @Inject
    ApprovalModel approvalModel;
    private int tabPosition;
    private int page = 1;
    ApproveManageAdapter mAdapter;
    List<ApprovalListEntity> mlist = new ArrayList<>();
    List<ApplyTypeData> applyTypeData = new ArrayList<>();
    private String mType = "";//审批类型


    public static ApprovalManagerFragment newInstance(int tabPosition) {
        ApprovalManagerFragment approvalManagerFragment = new ApprovalManagerFragment();
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, tabPosition);
        approvalManagerFragment.setArguments(args);
        return approvalManagerFragment;
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder().appComponent(appComponent).selfFragModule(new SelfFragModule(this)).build().inject(this);
    }

    //设置你审批类型
    public void setSecondType(String type, boolean isRequest){
        mType = type;
        if (isRequest) {
            getData(mType);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_approval_manage, container, false);
        binding.setLifecycleOwner(this);
        binding.rvAppManage.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new ApproveManageAdapter(mlist, this);
        mAdapter.bindToRecyclerView(binding.rvAppManage);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ApprovalListEntity entity = mlist.get(position);
                String type = entity.getApprover_type();
                String showOperation = "";
                switch (type) {
                    //租赁模块
                    case "machineRelease"://机械发布
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "mechanicsDetail", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "facilityRelease"://设备发布
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "equipmentDetails", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "carRelease"://车辆发布
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "vehicleDetails", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "houseRelease"://房产发布
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "propertyDetails", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "landRelease"://土地发布
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "landDetails", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "factoryRelease"://工厂发布
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "factoryDetails", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "farmmachineRelease"://农机发布
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "farmDetail", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "RentInOrderConfirm"://租入订单确认
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "receivedOrderApproval", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "RentInOrderPayment"://租入订单付款
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "receivedOrderApproval", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "RentOutOrderReceiv"://租出订单接单
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "receivedOrderApproval", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    //会员经营模块
                    case "applyJoinCompany"://申请加盟企业
                    case "memberRelieve"://会员解除申请
                    case "inviteJoinCompany"://邀请加盟企业

                        if (tabPosition == 0) {
                            showOperation = "1";
                        } else if (tabPosition == 1) {
                            showOperation = "2";
                        }
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "approvalDetail", showOperation, entity.get_id(), entity.getApproverStatus());
                        break;
                    case "memberEvaluate"://会员企业调级
                        if (tabPosition == 0) {
                            showOperation = "1";
                        } else if (tabPosition == 1) {
                            showOperation = "2";
                        }
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "memberEvaluate", showOperation, entity.get_id(), entity.getApproverStatus());
                        break;
                    //工队模块
                    case "teamPrice":
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "workquotionStatus", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "teamInfo":
                        approvalModel.getUrl(ApprovalManagerFragment.this, entity.getObjId(), "teamApproval", tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case"issueTender"://招标发布
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"hair",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "tenderBid"://招标定标
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"Calibration",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "abandonedBid"://招标废标
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"Scrap",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "addendum"://招标补遗
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"repair",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "issueBiding"://竞价发布
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"bidapproval",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "zcBidCancel"://竞价废标
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"Abandoned",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "zcBidDetermine"://竞价定标
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"Winning",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    case "zcBidAddendum"://竞价补遗
                        approvalModel.getUrl(ApprovalManagerFragment.this,entity.getObjId(),"approvalAddendum",tabPosition == 0 ? "1" : "", entity.get_id(), entity.getApproverStatus());
                        break;
                    default:
                        MToast.showToast(getActivity(), "请前往PC去处理该审批");
                        break;
                }
            }
        });
        binding.rvAppManage.addItemDecoration(
                new RecyclerCustomDecoration(
                        0f,
                        0f,
                        getResources().getDimension(R.dimen.dp10),
                        0f, getResources().getColor(R.color.color_main_bg)
                )
        );

        binding.rvAppManage.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.layout_empty_view);
        binding.srlCargoManage.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page += 1;
                getData(mType);

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getData(mType);
            }
        });
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        initIntentParams();

        getData(mType);
    }

    private void getData(String type) {
        switch (tabPosition) {
            case 0://代办事项
                approvalModel.getApplyPendingList(this, page, type);
                break;
            case 1://我发起的
                approvalModel.getQueryApproverListOfMine(this, page, type);
                break;
            case 2://已审批
                approvalModel.getApplyFinishedList(this, page, type);
                break;
            case 3://抄送我
                approvalModel.getNotifyListOfMine(this, page, type);
                break;
            case 4://全部
                approvalModel.getAllList(this, page, type);
                break;
        }

    }

    private void initIntentParams() {
        tabPosition = getArguments().getInt(RouterKey.TYPE);
    }

    /**
     * 同步数据
     *
     * @param data
     */
    public void refreshUIByData(ProListEntity<List<ApprovalListEntity>> data) {
        binding.srlCargoManage.finishRefresh();
        binding.srlCargoManage.finishLoadMore();

        if (data == null || data.getPageNumber() == 0) {
            mlist.clear();
        }
        if (data != null && data.getList() != null) {
            mlist.addAll(data.getList());
        }
        binding.srlCargoManage.setNoMoreData(mlist.size() == (data == null ? 0 : data.getTotalRow()));
        mAdapter.notifyDataSetChanged();
    }

    public void setApplyTypeDataList(List<ApplyTypeData> applyTypeData) {
        this.applyTypeData = applyTypeData;
    }

    public String getTypeContent(String key) {
        String keyStr = "";
        for (ApplyTypeData entity : applyTypeData) {
            if (entity.getKey().equals(key)) {
                keyStr = entity.getValue();
                break;
            }
        }
        return TextUtils.isEmpty(keyStr) ? key : keyStr;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(WebEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_APPROVAL_REFRESH) {
            if (tabPosition == 0) {
                binding.srlCargoManage.autoRefresh();
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_MEMBER_APPROVAL_REFRESH) {
            binding.srlCargoManage.autoRefresh();
            EventBus.getDefault().removeStickyEvent(event);
        }
    }
}
